<template>
  <div class="friend-details-panel">
    <div class="friend-details-content">
      <!-- 用户头像和名称 -->
      <div class="user-header-section">
        <q-avatar 
          class="user-avatar-large" 
          size="100px"
          :style="getAvatarStyle(friend.to_id || friend.user?.open_id || friend.user?.id)"
        >
          {{ displayName?.[0] || 'U' }}
        </q-avatar>
        <div class="user-name-large">{{ displayName }}</div>
        <div class="user-id-text" v-if="friend.user?.name && friend.remark">
          {{ friend.user.name }}
        </div>
      </div>

      <q-separator class="section-separator" />

      <!-- 备注信息 -->
      <div class="info-section">
        <div class="info-item">
          <div class="info-label">备注</div>
          <div class="info-value editable" @click="handleEditRemark">
            {{ friend.remark || '未设置' }}
            <q-icon name="edit" size="16px" class="edit-icon" />
          </div>
        </div>
        <div class="info-item" v-if="userAccount">
          <div class="info-label">账号</div>
          <div class="info-value">{{ userAccount }}</div>
        </div>
        <div class="info-item" v-if="userMobile">
          <div class="info-label">手机号</div>
          <div class="info-value">{{ userMobile }}</div>
        </div>
        <div class="info-item" v-if="userLocation">
          <div class="info-label">地区</div>
          <div class="info-value">{{ userLocation }}</div>
        </div>
      </div>

      <q-separator class="section-separator" />

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <div class="action-button" @click="handleSendMessage">
          <q-icon name="chat_bubble_outline" size="24px" />
          <div class="action-label">发消息</div>
        </div>
        <div class="action-button" @click="handleVoiceCall">
          <q-icon name="phone" size="24px" />
          <div class="action-label">语音通话</div>
        </div>
        <div class="action-button" @click="handleVideoCall">
          <q-icon name="videocam" size="24px" />
          <div class="action-label">视频通话</div>
        </div>
      </div>

      <q-separator class="section-separator" />

      <!-- 设置选项 -->
      <div class="settings-section">
        <div class="setting-item clickable" @click="handleSearchChatHistory">
          <div class="setting-label">查找聊天记录</div>
          <q-icon name="chevron_right" size="20px" class="chevron-icon" />
        </div>
        <div class="setting-item">
          <div class="setting-label">消息免打扰</div>
          <q-toggle v-model="doNotDisturb" @update:model-value="handleToggleDoNotDisturb" />
        </div>
        <div class="setting-item">
          <div class="setting-label">置顶聊天</div>
          <q-toggle v-model="pinChat" @update:model-value="handleTogglePinChat" />
        </div>
      </div>

      <q-separator class="section-separator" />

      <!-- 危险操作 -->
      <div class="danger-section">
        <div class="danger-item clickable" @click="handleClearChatHistory">
          <div class="danger-label">清空聊天记录</div>
        </div>
      </div>
    </div>

    <!-- 编辑备注对话框 -->
    <q-dialog v-model="showRemarkDialog">
      <q-card class="dialog-card">
        <q-card-section class="dialog-header">
          <div class="dialog-title">设置备注</div>
        </q-card-section>
        <q-card-section class="dialog-body">
          <q-input
            v-model="remarkText"
            placeholder="请输入备注名称"
            outlined
            dense
            autocomplete="off"
            autocapitalize="off"
            autocorrect="off"
            spellcheck="false"
            :loading="updatingRemark"
            maxlength="20"
            counter
            @keyup.enter="handleSaveRemark"
          />
        </q-card-section>
        <q-card-actions align="right" class="dialog-actions">
          <q-btn flat label="取消" @click="showRemarkDialog = false" class="dialog-btn" />
          <q-btn
            flat
            label="确定"
            color="primary"
            @click="handleSaveRemark"
            :loading="updatingRemark"
            class="dialog-btn dialog-btn-primary"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useQuasar } from 'quasar'
import { getAvatarStyle } from '@/utils/avatar'
import { updateFriendRemark } from '../services/im-friendship'
import { useChatStore } from '../stores/chat'
import { getUserData } from '../services/im-user'

const props = defineProps<{
  friend: any
}>()

const emit = defineEmits<{
  'send-message': [friendId: string]
  'update-remark': [friendId: string, remark: string]
  'voice-call': [friendId: string, friendName: string]
  'video-call': [friendId: string, friendName: string]
}>()

const $q = useQuasar()
const chatStore = useChatStore()

// 状态
const showRemarkDialog = ref(false)
const remarkText = ref('')
const updatingRemark = ref(false)
const doNotDisturb = ref(false)
const pinChat = ref(false)
const userData = ref<any>(null)
const loadingUserData = ref(false)

// 计算属性
const displayName = computed(() => {
  return props.friend?.remark || props.friend?.user?.name || props.friend?.to_id || '未知用户'
})

const userAccount = computed(() => {
  return userData.value?.user_id || props.friend?.user?.name || props.friend?.to_id || ''
})

const userMobile = computed(() => {
  return userData.value?.mobile || props.friend?.user?.mobile || ''
})

const userLocation = computed(() => {
  return userData.value?.location || props.friend?.user?.location || ''
})

// 加载用户详细信息
const loadUserData = async () => {
  if (!props.friend?.to_id) return
  
  loadingUserData.value = true
  try {
    // to_id 可能是 open_id，尝试直接使用
    const userId = props.friend.to_id
    try {
      const data = await getUserData(userId)
      userData.value = data
    } catch (error: any) {
      // 如果使用 to_id 失败，尝试使用 user.id 或 user.snowflake_id
      if (props.friend?.user?.id) {
        try {
          const data = await getUserData(String(props.friend.user.id))
          userData.value = data
        } catch (e) {
          console.warn('使用 user.id 获取用户数据失败:', e)
          userData.value = null
        }
      } else {
        userData.value = null
      }
    }
  } catch (error: any) {
    console.error('加载用户详细信息失败:', error)
    userData.value = null
  } finally {
    loadingUserData.value = false
  }
}

// 组件挂载时加载用户数据
onMounted(() => {
  loadUserData()
})

// 处理编辑备注
const handleEditRemark = () => {
  remarkText.value = props.friend?.remark || ''
  showRemarkDialog.value = true
}

// 处理保存备注
const handleSaveRemark = async () => {
  if (!props.friend?.to_id) return
  
  updatingRemark.value = true
  try {
    await updateFriendRemark(props.friend.to_id, remarkText.value.trim() || undefined)
    emit('update-remark', props.friend.to_id, remarkText.value.trim())
    showRemarkDialog.value = false
    $q.notify({
      type: 'positive',
      message: '备注已更新',
    })
  } catch (error: any) {
    $q.notify({
      type: 'negative',
      message: error.message || '更新备注失败',
    })
  } finally {
    updatingRemark.value = false
  }
}

// 处理发消息
const handleSendMessage = () => {
  if (props.friend?.to_id) {
    emit('send-message', props.friend.to_id)
  }
}

// 处理语音通话
const handleVoiceCall = () => {
  if (props.friend?.to_id) {
    emit('voice-call', props.friend.to_id, displayName.value)
  }
}

// 处理视频通话
const handleVideoCall = () => {
  if (props.friend?.to_id) {
    emit('video-call', props.friend.to_id, displayName.value)
  }
}

// 处理查找聊天记录
const handleSearchChatHistory = () => {
  $q.notify({
    type: 'info',
    message: '查找聊天记录功能待实现',
    position: 'top',
  })
}

// 处理切换免打扰
const handleToggleDoNotDisturb = (value: boolean) => {
  // TODO: 实现免打扰设置
  console.log('免打扰:', value)
}

// 处理切换置顶
const handleTogglePinChat = (value: boolean) => {
  // TODO: 实现置顶设置
  console.log('置顶:', value)
}

// 处理清空聊天记录
const handleClearChatHistory = () => {
  if (!props.friend?.to_id) return
  
  $q.dialog({
    title: '确认清空',
    message: `确定要清空与 ${displayName.value} 的聊天记录吗？此操作只删除本地存储的消息，不会影响服务器上的消息。`,
    cancel: true,
    persistent: true,
  }).onOk(async () => {
    try {
      const { clearUserChatMessages } = await import('../services/secure-storage')
      await clearUserChatMessages(props.friend.to_id)
      await chatStore.clearUserMessages(props.friend.to_id, [])
      $q.notify({
        type: 'positive',
        message: '已清空聊天记录',
      })
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.message || '清空聊天记录失败',
      })
    }
  })
}
</script>

<style scoped lang="sass">
.friend-details-panel
  display: flex
  flex-direction: column
  height: 100%
  background: #F7F7F7
  overflow-y: auto
  padding: 0 20px

.friend-details-content
  flex: 1
  display: flex
  flex-direction: column
  max-width: 100%
  margin: 0 auto
  width: 100%

// 用户头部区域
.user-header-section
  display: flex
  flex-direction: column
  align-items: center
  padding: 48px 24px 36px 24px
  background: #FFFFFF
  border-radius: 12px
  margin-top: 20px
  margin-bottom: 12px
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05)
  
  .user-avatar-large
    color: white
    font-weight: 600
    font-size: 40px
    margin-bottom: 20px
    border: 2px solid rgba(0, 0, 0, 0.05)
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08)
    
  .user-name-large
    font-size: 20px
    font-weight: 600
    color: #191919
    margin-bottom: 8px
    letter-spacing: -0.3px
    
  .user-id-text
    font-size: 14px
    color: #8E8E93
    letter-spacing: -0.1px

// 分隔线
.section-separator
  margin: 0
  background: rgba(0, 0, 0, 0.08)
  height: 0.5px
  display: none

// 信息区域
.info-section
  background: #FFFFFF
  padding: 0 24px
  border-radius: 12px
  margin-bottom: 12px
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05)
  
  .info-item
    display: flex
    align-items: center
    justify-content: space-between
    padding: 18px 0
    border-bottom: 0.5px solid rgba(0, 0, 0, 0.08)
    
    &:last-child
      border-bottom: none
      
    .info-label
      font-size: 16px
      font-weight: 500
      color: #191919
      letter-spacing: -0.2px
      
    .info-value
      font-size: 16px
      color: #8E8E93
      text-align: right
      flex: 1
      margin-left: 16px
      overflow: hidden
      text-overflow: ellipsis
      white-space: nowrap
      
      &.editable
        display: flex
        align-items: center
        justify-content: flex-end
        gap: 8px
        cursor: pointer
        transition: color 0.2s ease
        
        &:hover
          color: #007AFF
          
        .edit-icon
          opacity: 0.6
          transition: opacity 0.2s ease
          
        &:hover .edit-icon
          opacity: 1

// 操作按钮区域
.action-buttons
  display: flex
  justify-content: space-around
  padding: 24px
  background: #FFFFFF
  border-radius: 12px
  margin-bottom: 12px
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05)
  
  .action-button
    display: flex
    flex-direction: column
    align-items: center
    gap: 10px
    cursor: pointer
    padding: 12px 16px
    border-radius: 10px
    transition: all 0.2s ease
    min-width: 80px
    
    &:hover
      background: rgba(0, 0, 0, 0.04)
      transform: translateY(-1px)
      
    &:active
      background: rgba(0, 0, 0, 0.08)
      transform: translateY(0)
      
    .q-icon
      color: #007AFF
      
    .action-label
      font-size: 14px
      color: #191919
      font-weight: 500
      letter-spacing: -0.1px

// 设置区域
.settings-section
  background: #FFFFFF
  padding: 0 24px
  border-radius: 12px
  margin-bottom: 12px
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05)
  
  .setting-item
    display: flex
    align-items: center
    justify-content: space-between
    padding: 18px 0
    border-bottom: 0.5px solid rgba(0, 0, 0, 0.08)
    
    &:last-child
      border-bottom: none
      
    &.clickable
      cursor: pointer
      transition: background-color 0.2s ease
      
      &:hover
        background: rgba(0, 0, 0, 0.02)
        margin: 0 -24px
        padding-left: 24px
        padding-right: 24px
        border-radius: 8px
        
    .setting-label
      font-size: 16px
      font-weight: 500
      color: #191919
      letter-spacing: -0.2px
      
    .chevron-icon
      color: #C7C7CC

// 危险操作区域
.danger-section
  background: #FFFFFF
  padding: 0 24px
  border-radius: 12px
  margin-bottom: 20px
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05)
  
  .danger-item
    display: flex
    align-items: center
    justify-content: center
    padding: 18px 0
    cursor: pointer
    transition: background-color 0.2s ease
    
    &.clickable
      &:hover
        background: rgba(255, 59, 48, 0.05)
        margin: 0 -24px
        padding-left: 24px
        padding-right: 24px
        border-radius: 8px
        
      &:active
        background: rgba(255, 59, 48, 0.08)
        
    .danger-label
      font-size: 16px
      font-weight: 500
      color: #FF3B30
      letter-spacing: -0.2px

// 对话框样式
.dialog-card
  min-width: 300px
  border-radius: 12px
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12)
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Helvetica Neue", Helvetica, Arial, sans-serif

.dialog-header
  padding: 24px 24px 16px 24px
  border-bottom: 1px solid rgba(0, 0, 0, 0.06)

.dialog-title
  font-size: 20px
  font-weight: 600
  color: #1D1D1F
  letter-spacing: -0.3px
  line-height: 1.4

.dialog-body
  padding: 20px 24px

.dialog-actions
  padding: 12px 20px 20px 20px
  border-top: 1px solid rgba(0, 0, 0, 0.06)

.dialog-btn
  font-size: 15px
  font-weight: 500
  padding: 8px 16px
  min-width: 64px
  letter-spacing: -0.1px
  
  &.dialog-btn-primary
    font-weight: 600
</style>

